package com.baizhi.controller;

import com.baizhi.bean.User;
import com.baizhi.service.UserService;
import com.baizhi.util.ValidateCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RequestMapping("user")
@Controller
public class UserController {

    @Autowired
    UserService userService;

    //退出登录
    @RequestMapping("logout")
    public String logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();//退出登录
        return "redirect:/login.jsp";
    }

    //用来处理身份认证
    @RequestMapping("login")
    public String login(String username, String password, HttpServletRequest request) throws Exception {
        //比较验证码
        request.setCharacterEncoding("utf-8");
        String randomCode= (String) request.getSession().getAttribute("validateCode");
        String code=request.getParameter("code");
        try {
            if (code.equalsIgnoreCase(randomCode)) {
                //获取主体对象
                Subject subject = SecurityUtils.getSubject();
                subject.login(new UsernamePasswordToken(username, password));
                return "redirect:/index.jsp";
            } else {
                throw new RuntimeException("验证码错误");
            }
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户名错误");
        } catch (IncorrectCredentialsException credentialsException) {
            credentialsException.printStackTrace();
            System.out.println("密码错误");
        }catch (RuntimeException e){
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return "redirect:/login.jsp";
}

    //用户注册
    @RequestMapping("register")
    public String register(User user) {
        try {
            userService.register(user);
            return "redirect:/login.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/register.jsp";
        }
    }

    //验证码方法
    @RequestMapping(value = "getImage", method = RequestMethod.GET)
    public void getImg(HttpServletRequest request, HttpServletResponse response) {
        //生成验证码
        ValidateCode validateCode = new ValidateCode(130, 35, 30, "validateCode");
        validateCode.getCode(request, response);
    }

}
